<template>
  <div>
    <Bread></Bread>
    <el-card>
      <el-button type="primary" @click="addCate">添加分类</el-button>
      <!-- 表格 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        :show-index="true"
        index-text="#"
        border
        :show-row-hover="false"
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color:lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color:red"></i>
        </template>

        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" size="mini" v-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning" size="mini" v-if="scope.row.cat_level === 2">三级</el-tag>
        </template>

        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" @click="cateEdit(scope.row)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="cateDelete(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>

      <!-- 分类 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="obj.pagenum"
        :page-sizes="[1, 3, 5, 7]"
        :page-size="obj.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加分类 -->
    <el-dialog title="添加分类" :visible.sync="cateForm" width="50%" @close="addCateClosed">
      <el-form :model="addCateForm" :rules="rules" label-width="100px" ref="addCateFormRef">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCateForms.cat_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="addCateForm" :rules="rules" label-width="100px">
        <el-form-item label="父级分类：">
          <!-- options 用来指定数据源 -->
          <el-cascader
            v-model="selectedKeys"
            :options="parentCateList"
            :props="{ 
              expandTrigger: 'hover',
              checkStrictly: true,
              value:'cat_id',
              label:'cat_name',
              children:'children'}"
            @change="handleChange"
            :clearable="true"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cateForm = false">取 消</el-button>
        <el-button type="primary" @click="addCates">确 定</el-button>
      </div>
    </el-dialog>


    <!-- 编辑分类 -->
     <el-dialog title="编辑分类" :visible.sync="cateForms" width="50%" @close="addCateClosed">
      <el-form :model="addCateForms" :rules="rules" label-width="100px" ref="addCateFormRef">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCateForms.cat_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cateForms = false">取 消</el-button>
        <el-button type="primary" @click="cateEdits">确 定</el-button>
      </div>
     </el-dialog>
  </div>
</template>
<script>
import Bread from "@/components/breadmenu.vue";
export default {
  components: { Bread },
  data() {
    return {
      cateForm: false,
      cateForms: false,
      obj: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      cateList: [],
      total: 0,
      columns: [
        {
          label: "分类名称",
          prop: "cat_name"
        },
        {
          label: "是否有效",
          type: "template",
          template: "isok"
        },
        {
          label: "排序",
          type: "template",
          template: "order"
        },
        {
          label: "操作",
          type: "template",
          template: "opt"
        }
      ],
      addCateForm: {
        cat_name: "",
        cat_pid: 0,
        cat_level: 0
      },
      addCateForms:{},
      rules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
      },
      parentCateList: [],
      // 选中的父级分类ID数组
      selectedKeys: []
    };
  },
  mounted() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.obj
      });
      console.log(res.data);
      this.cateList = res.data.result;
      this.total = res.data.total;
    },
    handleSizeChange(val) {
      this.obj.pagesize = val;
      this.getCateList();
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.obj.pagenum = val;
      this.getCateList();
      console.log(`当前页: ${val}`);
    },
    addCate() {
      this.getParentCateList();
      this.cateForm = true;
    },
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 }
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取父级分类数据失败");
      }

      console.log(res.data);
      this.parentCateList = res.data;
    },
    // 级联选择发生变化触发
    handleChange() {
      console.log(this.selectedKeys);
      if (this.selectedKeys.length > 0) {
        this.addCateForm.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ];

        this.addCateForm.cat_level = this.selectedKeys.length;
      } else {
        this.addCateForm.cat_pid = 0;

        this.addCateForm.cat_level = 0;
      }
    },
    // 点击级联确定
    addCates() {
      console.log(this.addCateForm)
      this.$refs.addCateFormRef.validate(async value=>{
        if(value){
          const {data:res} = await this.$http.post('categories',this.addCateForm)
          if(res.meta.status !== 201){
            return this.$message.error("添加分类失败！")
          }

          this.$message.success("添加分类成功！")
          this.getCateList()
          this.cateForm = false
        }
      })
    },
    addCateClosed() {
      this.$refs.addCateFormRef.resetFields();
      this.selectedKeys = [];
      this.addCateForm.cat_pid = 0;

      this.addCateForm.cat_level = 0;
    },
    cateEdit(info){
      console.log(info)
      this.cateForms = true
      this.addCateForms = info
    },
    cateEdits(){
       this.$refs.addCateFormRef.validate(async value=>{
        if(value){
          const {data:res} = await this.$http.put('categories/'+this.addCateForms.cat_id,this.addCateForms)
          if(res.meta.status !== 200){
            return this.$message.error("更新分类失败！")
          }

          this.$message.success("更新分类成功！")
          this.getCateList()
          this.cateForms = false
        }
      })
    },
    cateDelete(id){
      console.log(id)
       this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http.delete("categories/" + id).then(res => {
            console.log(res);
            if (res.data.meta.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.getCateList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  }
};
</script>
<style lang="scss">
.el-card {
  margin-top: 10px;
}
.zk-table {
  margin-top: 10px;
}
.el-cascader {
  width: 100%;
}
</style>